package com.beyondbit.demo.service.impl;

import com.beyondbit.demo.common.IdGenerator;
import com.beyondbit.demo.constant.MessageConstant;
import com.beyondbit.demo.dao.UserMapper;
import com.beyondbit.demo.entity.User;
import com.beyondbit.demo.entity.query.UserQuery;
import com.beyondbit.demo.service.BaseUserServiceException;
import com.beyondbit.demo.service.UserExistsException;
import com.beyondbit.demo.service.UserService;
import com.beyondbit.web.infrastructure.entity.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: lvfahai
 * @Date: 2020/3/10 11:28
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public Page<User> query(UserQuery query) {
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        List<User> list = userMapper.query(query);

        return Page.of(list);
    }

    @Override
    public User get(String id) {
        return userMapper.get(id);
    }

    @Override
    public void add(User user) throws BaseUserServiceException {
        User existUser = userMapper.getUser(user.getUserUid());

        if (existUser != null) {
            throw new UserExistsException(MessageConstant.USER_EXISTS_EXCEPTION);
        } else {
            user.setId(idGenerator.newId());
            user.setDateCreated(new Date());
            userMapper.insert(user);
        }
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(String id) {
        userMapper.delete(id);
    }

    @Override
    public User selUserByUser(String userUid) {
        return userMapper.selUserByUser(userUid);
    }
}
